package Andrew;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * A simple class that opens a socket, sends a message to the server, and
 * terminates.
 * 
 * @author Graeme Stevenson (graeme.stevenson@ucd.ie)
 */
public class TestClient {

	/**
	 * The server host name.
	 */
	public String my_serverHost;

	/**
	 * The server port.
	 */
	public int my_serverPort;

	/**
	 * Sets the client up with the server details.
	 * 
	 * @param the_serverHost
	 *            the server host name.
	 * @param the_serverPort
	 *            the server port.
	 */
	public TestClient(final String the_serverHost, final int the_serverPort) {
		my_serverHost = the_serverHost;
		my_serverPort = the_serverPort;
	}

	/**
	 * Creates a connection to the server and sends a message.
	 * 
	 * @param a
	 *            and b the numbers to send to the server.
	 */
	public void sendMessage(final String s) {
		try {
			// Create a connection to the server.
			final Socket toServer = new Socket(my_serverHost, my_serverPort);

			// Wrap a PrintWriter round the socket output stream.
			// Read the javadoc to understand (1) the method arguments, and (2)
			// why
			// we do this rather than writing to raw sockets.
			final PrintWriter out = new PrintWriter(toServer.getOutputStream(),
					true);
			out.println(s);
			final BufferedReader in = new BufferedReader(new InputStreamReader(
					toServer.getInputStream()));
			// for(int i = 0; i<15; i++){
			System.out.println(in.readLine() + "\n");
			// }

			// Print the message to the console

			// EXERCISE: Extend this code to
			// 1. Read the response from the server.
			// 2. Print the response out to the console.
			// This reads the response

			// Read in the response from the server and prints the response

			// tidy up
			out.close();
			in.close();
			toServer.close();
		} catch (final IOException ioe) {
			ioe.printStackTrace();
		} catch (final SecurityException se) {
			se.printStackTrace();
		}
	}
}
